package com.xkstream.client.ui.live;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.common.AppConfig;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.AnchorInfo;
import com.xkstream.client.entity.FirVersion;
import com.xkstream.client.entity.Game;
import com.xkstream.client.entity.ReceiveGift;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.UserInfo;
import com.xkstream.client.entity.kt.GiftRankingData;
import com.xkstream.client.presenter.StartLiveContract;
import com.xkstream.client.presenter.StartLivePresenter;
import com.xkstream.client.service.DownloadService;
import com.xkstream.client.service.JPushUtil;
import com.xkstream.client.ui.adapter.ReceiveGiftRankAdapter;
import com.xkstream.client.ui.kt.UploadLogFileActivity;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.PreferenceUtils;
import com.xkstream.client.view.BottomPushPopupWindow;
import com.xkstream.client.view.CircleImageView;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/3/15.
 */

public class StartLiveActivity extends BaseActivity<StartLiveContract.Presenter> implements StartLiveContract.View {
    @BindView(R.id.llUserInfo)
    RelativeLayout llUserInfo;
    @BindView(R.id.llLiveRoomInfo)
    LinearLayout llLiveRoomInfo;
    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    //    @BindView(R.id.rgChoose)
//    RadioGroup rgChoose;
//    @BindView(R.id.rbNormal)
//    RadioButton rbNormal;
//    @BindView(R.id.rbHd)
//    RadioButton rbHd;
//    @BindView(R.id.rbSd)
//    RadioButton rbsd;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvRoomNum)
    TextView tvRoomNum;
    @BindView(R.id.tvGameType)
    TextView tvGameType;
    @BindView(R.id.ivGiftRank)
    ImageView ivGiftRank;
    @BindView(R.id.tvRoomType)
    TextView tvRoomType;
    private Context context;
    @BindView(R.id.edtRoomName)
    EditText edtRoomName;
    @BindView(R.id.edtRoomPassword)
    EditText edtRoomPassword;
    //    @BindView(R.id.rlGameType)
//    RelativeLayout rlGameType;
    @BindView(R.id.rlRoomType)
    RelativeLayout rlRoomType;
    @BindView(R.id.edtNotice)
    EditText edtNotice;
    @BindView(R.id.tvVersion)
    TextView tvVersion;

    @BindView(R.id.tvStartLive)
    TextView tvStartLive;
    @BindView(R.id.btnStartLive)
    Button btnStartLive;

    @BindString(R.string.update_hint)
    String updateHint;

    private long lastClickBackTime = -1;
    private static final int QUIT_CONFIRM_TIME = 3000;


    private List<Game> games = new ArrayList<>();


    private ReceiveGiftRankAdapter receiveGiftRankAdapter;

    private List<ReceiveGift> receiveGiftlist = new ArrayList<>();

    private List<ReceiveGift> total = new ArrayList<>();

    private List<ReceiveGift> week = new ArrayList<>();

    private List<ReceiveGift> month = new ArrayList<>();


    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_preparelive);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        tvVersion.setText("Version" + DeviceUtils.getVersionName(this));
        context = this;
        llUserInfo.getBackground().setAlpha(40);
//        llLiveRoomInfo.getBackground().setAlpha(40);
        ivHeader.setBorderColor(getResources().getColor(R.color.white));
        ivHeader.setBorderWidth(4);
        User user = Application.getUser();
        String anchorDes = PreferenceUtils.getString(PreferenceUtils.ANCHOR_DES + user.getUser_code());
        String anchorTitle = PreferenceUtils.getString(PreferenceUtils.ANCHOR_TITLE + user.getUser_code());
        if (!TextUtils.isEmpty(anchorDes)) {
            edtNotice.setText(anchorDes);
            edtNotice.setSelection(anchorDes.length());
        }
        if (!TextUtils.isEmpty(anchorTitle)) {
            edtRoomName.setText(anchorTitle);
            edtRoomName.setSelection(anchorTitle.length());
        }
        prepareViews();
        presenter = new StartLivePresenter(this);

        presenter.checkVersion();
        JPushUtil jpushUtil = JPushUtil.getInstance();
        if (!TextUtils.isEmpty(Application.getUser().getUser_code())) {
            if (AppConfig.isTest()) {
                jpushUtil.setAliasWithTags(Application.getUser().getUser_code(), JPushUtil.initTags());
            } else {
                jpushUtil.setAliasWithTags(Application.getUser().getUser_code(), JPushUtil.initTags());
            }
        }
    }

    private void prepareViews() {
        String userStr = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(userStr, User.class);
        AnchorInfo anchor = user.getAnchor();
        UserInfo extInfo = user.getExt_info();
        AsyncImage.loadPhoto(context, extInfo.getHead_icon(), ivHeader);
        if (TextUtils.isEmpty(extInfo.getNickname())) {
            tvName.setText("暂无房间名称");
        } else {
            tvName.setText(extInfo.getNickname());
        }
        tvRoomNum.setText(anchor.getRoom_id_pk() + "");
    }


    @OnClick({R.id.btnStartLive, R.id.rlGameType, R.id.ivGiftRank, R.id.rlRoomType
            , R.id.ivSettings})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStartLive:
                anchorOnOff();
                break;
            case R.id.rlGameType:
                //      createGiftNumDialog();
                //  createDialog();
                loadGameType();
                break;
            case R.id.ivGiftRank:
                //            createGiftNumDialog();
                loadGiftNumRanking();
                break;
            case R.id.rlRoomType:
                createSelectRoomTypeDialog();
                break;
            case R.id.ivSettings:
                jumpToActivity(UploadLogFileActivity.class);
                break;
        }
    }

    //主播上下线
    private void anchorOnOff() {
        String userStr = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(userStr, User.class);
        String id = user.getUser_code();
        int roomId = user.getAnchor().getRoom_id_pk();
//        Game game = (Game) tvGameType.getTag();
        /*if (TextUtils.isEmpty(edtRoomName.getText().toString())) {
            showToast("请输入房间名称");
            return;
        }*/
//        if (game == null) {
//            showToast("请选择游戏");
//             return;
//        }
        String roomTypeText = tvRoomType.getText().toString();
        String roomType = "0";
        //0普通1vip
        if (roomTypeText.equals("VIP房间")) {
            roomType = "1";
        } else if (roomTypeText.equals("普通房间")) {
            roomType = "0";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("anchor_user_code", id);
        if (!TextUtils.isEmpty(edtNotice.getText().toString())) {
            params.put("anchor_description", edtNotice.getText().toString());
        }
        params.put("anchor_status", "1");
        //       params.put("game_type",game.getId_pk());
        //       params.put("room_id_pk", roomId + "");
        params.put("room_type", roomType);
        params.put("anchor_title", user.getExt_info().getNickname());
        if (roomType.equals("1")) {
            if (TextUtils.isEmpty(edtRoomPassword.getText().toString())) {
                showToast("请输入房间密码");
                return;
            } else {
                params.put("room_password", edtRoomPassword.getText().toString());
            }
        }
        params.put("game_type", "2");
        presenter.anchorOnOff(params);
    }

    private void loadGiftNumRanking() {
        String strUser = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(strUser, User.class);
        presenter.getGiftRanking(user.getUser_code());
    }

    private void createGiftNumDialog() {

        View view = View.inflate(context, R.layout.layout_gifrank_dialog, null);
        Dialog dialog = new Dialog(context, R.style.Theme_Transparent);
        //     final AlertDialog dialog = new AlertDialog.Builder(this).create();
        ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
        TextView tvToady = (TextView) view.findViewById(R.id.tvToday);
        TextView tvWeek = (TextView) view.findViewById(R.id.tvWeek);
        TextView tvMonth = (TextView) view.findViewById(R.id.tvMonth);
        ListView lvGiftNum = (ListView) view.findViewById(R.id.lvGiftNum);
        //   TextView tvTotal = (TextView) view.findViewById(R.id.tvTotal);
        receiveGiftRankAdapter = new ReceiveGiftRankAdapter(context, receiveGiftlist);
        lvGiftNum.setAdapter(receiveGiftRankAdapter);
        setDialogItemSelected(tvToady, tvWeek, tvMonth, 1);
        MyDialogClickListener listener = new MyDialogClickListener(dialog, ivClose, tvToady, tvWeek, tvMonth);
        dialog.setContentView(view);

        dialog.setCanceledOnTouchOutside(true);
        tvToady.setOnClickListener(listener);
        tvWeek.setOnClickListener(listener);
        tvMonth.setOnClickListener(listener);
        ivClose.setOnClickListener(listener);
        dialog.show();
    }

    @Override
    public void setPresenter(StartLiveContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showRankingData(GiftRankingData data) {
        if (data != null) {
            week = data.getWeek();
            total = data.getTotal();
            month = data.getMonth();
            createGiftNumDialog();
        }

    }

    @Override
    public void showAnchorOnOffResult(BaseData data, Map<String, Object> params) {
        if (data.getCode() == 1) {
            User user = Application.getUser();
            boolean hasDescription = params.containsKey("anchor_description");
            if (hasDescription) {
                String anchor_description = params.get("anchor_description").toString();
                PreferenceUtils.putString(PreferenceUtils.ANCHOR_DES + user.getUser_code(), anchor_description);
            }
            String anchor_title = params.get("anchor_title").toString();
            PreferenceUtils.putString(PreferenceUtils.ANCHOR_TITLE + user.getUser_code(), anchor_title);

            Intent intent = new Intent();
//            intent.putExtra("gameType", data.getData().getGame_type());
            intent.setClass(StartLiveActivity.this, LiveRoomActivity_V2.class);
            startActivity(intent);
        } else {
            showToast("请两分钟后重试");
        }
    }

    @Override
    public void showVersionInfo(FirVersion firVersion) {
        int localVersion = Integer.parseInt(DeviceUtils.getVersionCode(this));
        int latestVersion = Integer.parseInt(firVersion.getVersion());
        if (latestVersion > localVersion) {
            showUpdateDialog(firVersion);
        }

    }

    private void showUpdateDialog(FirVersion version) {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(updateHint);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setSingleButton();
        dialog.setListener(() -> {
            Intent it = new Intent(StartLiveActivity.this, DownloadService.class);
            it.putExtra("apkUrl", version.getInstallUrl());
            startService(it);
            ServiceConnection conn = new ServiceConnection() {
                @Override
                public void onServiceDisconnected(ComponentName name) {

                }

                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {

                }
            };
            bindService(it, conn, BIND_AUTO_CREATE);

            tvStartLive.setText(R.string.updating);
            btnStartLive.setEnabled(false);
        });
        dialog.show();
    }


    private class MyDialogClickListener implements View.OnClickListener {
        Dialog dialog;
        TextView tvToday;
        TextView tvWeek;
        TextView tvMonth;
        ImageView ivClose;
        //     TextView tvTotal;

        MyDialogClickListener(Dialog dialog, ImageView ivClose, TextView tvToday, TextView tvWeek, TextView tvMonth) {
            this.dialog = dialog;
            this.tvToday = tvToday;
            this.tvWeek = tvWeek;
            this.tvMonth = tvMonth;
            this.ivClose = ivClose;
            //       this.tvTotal = tvTotal;
        }


        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.ivClose) {
                dialog.dismiss();
            } else if (v.getId() == R.id.tvToday) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth, 0);

            } else if (v.getId() == R.id.tvWeek) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth, 1);

            } else if (v.getId() == R.id.tvMonth) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth,
                        2);
            }
        }
    }

    private void setDialogItemSelected(TextView tvToday, TextView tvWeek, TextView tvMonth, int position) {
        switch (position) {
            case 0:
                tvToday.setBackground(getResources().getDrawable(R.drawable.shape_giftlefttitle_bg));
                tvToday.setTextColor(getResources().getColor(R.color.black));
                tvWeek.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setBackground(null);
                tvMonth.setTextColor(getResources().getColor(R.color.white));
                tvMonth.setBackground(null);
                receiveGiftlist.clear();
                receiveGiftlist.addAll(week);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
            case 1:
                tvToday.setBackground(null);
                tvToday.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setTextColor(getResources().getColor(R.color.black));
                tvWeek.setBackgroundColor(getResources().getColor(R.color.white));
                tvMonth.setTextColor(getResources().getColor(R.color.white));
                tvMonth.setBackground(null);
                receiveGiftlist.clear();
                receiveGiftlist.addAll(month);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
            case 2:
                tvToday.setBackground(null);
                tvToday.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setBackground(null);
                tvMonth.setTextColor(getResources().getColor(R.color.black));
                tvMonth.setBackground(getResources().getDrawable(R.drawable.shape_giftrighttitle_bg));
                receiveGiftlist.clear();
                receiveGiftlist.addAll(total);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
        }
    }

    private int getGiftPriceTotal() {
        int total = 0;
        for (int i = 0; i < receiveGiftlist.size(); i++) {
            if (!TextUtils.isEmpty(receiveGiftlist.get(i).getGift_value())) {
                total += Double.parseDouble(receiveGiftlist.get(i).getGift_value());
            }
        }
        return total;
    }

//    @Override
//    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        int id = group.getCheckedRadioButtonId();
//        switch (id) {
//            case R.id.rbNormal:
//                showToast("rbNormal");
//                break;
//            case R.id.rbHd:
//                showToast("rbHd");
//                break;
//            case R.id.rbSd:
//                showToast("rbSd");
//                break;
//        }
//    }

    @Override
    public void onBackPressed() {
        long curTime = System.currentTimeMillis();
        if ((curTime - lastClickBackTime) >= QUIT_CONFIRM_TIME) {
            lastClickBackTime = curTime;
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
        } else {
            AppManager.getAppManager().AppExit(context);
        }
    }

    private void createSelectGameDialog() {
        final BottomPushPopupWindow popupWindow = new BottomPushPopupWindow(context, games);
        popupWindow.show(this);
        View view = popupWindow.getContentView();
        ListView lvGame = (ListView) view.findViewById(R.id.lvGame);
        lvGame.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Game game = games.get(position);
                tvGameType.setText(game.getGame_name());
                tvGameType.setTag(game);
                popupWindow.dismiss();
            }
        });
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private void createSelectRoomTypeDialog() {
        final BottomPushPopupWindow popupWindow = new BottomPushPopupWindow(context, 1);
        popupWindow.show(this);
        View view = popupWindow.getContentView();
        TextView tvVipRoom = (TextView) view.findViewById(R.id.tvVipRoom);
        TextView tvNormalRoom = (TextView) view.findViewById(R.id.tvNormalRoom);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        tvVipRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvRoomType.setText("VIP房间");
                popupWindow.dismiss();
                edtRoomPassword.setVisibility(View.VISIBLE);
            }
        });
        tvNormalRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvRoomType.setText("普通房间");
                popupWindow.dismiss();
                edtRoomPassword.setVisibility(View.GONE);
            }
        });

    }

    private void loadGameType() {
        presenter.getGameType();
    }
}
